package com.uchengwang.ui.cm_ui.uu.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.uchengwang.R;
import com.uchengwang.functions.db.manager.LiteOrmDBUtil;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.ThemeConfig;
import com.uchengwang.functions.http.config.UUConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.IHttpManager;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.functions.http.manager.OSSManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ActivityTitleBar;
import com.uchengwang.ui.base_ui.ui.AllBaseActivity;
import com.uchengwang.ui.cm_ui.release.ui.FastChoosePhotoActivity;
import com.uchengwang.ui.cm_ui.ucity.listener.RxBusResultSubscriber;
import com.uchengwang.ui.cm_ui.uu.adapter.ReleaseSpeekAdapter;
import com.uchengwang.ui.cm_ui.uu.bean.SpeekBean;
import com.uchengwang.ui.listener.PermissionsListener;
import com.uchengwang.ui.utils.DialogUtils;
import com.uchengwang.ui.utils.ImageManagerUtils;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.MapManager;
import com.uchengwang.ui.utils.NetwotkUtil;
import com.uchengwang.ui.utils.PermissionUtils;
import com.uchengwang.ui.utils.PopupUtils;
import com.uchengwang.ui.utils.UCommonUtil;
import com.uchengwang.ui.view.MyGridView;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;
import cn.finalteam.rxgalleryfinal.ui.RxGalleryListener;
import me.shaohui.advancedluban.OnMultiCompressListener;


/**
 * Created by U城网 on 2017/6/4.
 * 发布享说
 */

public class ReleaseSpeekActivity extends AllBaseActivity implements View.OnClickListener{
    private EditText edit;
    private RelativeLayout choose_rl, location_rl, look_rl;
    private MyGridView gv;
    private TextView choose, location, look_type;
    private Button release;

    private ArrayList<MediaBean> medias = new ArrayList<>();//返回多张图片地址
    private List<String> imageList = new ArrayList<>();//选择本地图片,得到的本地图片的集合 提交到oss
    private int hasImageNum;//当前已经选择的照片数量
    private String roll_imgs ;//图片上传到oss成功后，拼接的结果
    private String editString, locationS;
    private ReleaseSpeekAdapter adapter;
    private ActivityTitleBar titleBa;
    private String saveLocation;
    private PopupUtils popupUtils;
    private List<SpeekBean> speekBeanList;
    private AlertDialog dialog;
    private boolean isAllow = true;
    private int imgsHeight, imgsWidth;//单张图片时上传宽高
    private int releaseType;//0发布享说(默认)  1发布U城话题
    private long themeId;//发布话题信息时需要

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_speek);
        releaseType = getIntent().getIntExtra(BaseConfig.PUB_TYPE, 0);
        themeId = getIntent().getLongExtra(BaseConfig.TOPIC_ID, -1);

        initView();

        titleBa.setLeftListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                back();
            }
        });
    }

    private void initView() {
        titleBa = (ActivityTitleBar) findViewById(R.id.releaseSpeek_titleBa);


        edit = (EditText) findViewById(R.id.releaseSpeek_edit);
        choose_rl = (RelativeLayout) findViewById(R.id.releaseSpeek_choose_rl);

        location_rl = (RelativeLayout) findViewById(R.id.releaseSpeek_location_rl);
        location_rl.setOnClickListener(this);
        look_rl = (RelativeLayout) findViewById(R.id.releaseSpeek_look_rl);
        look_rl.setOnClickListener(this);

        gv = (MyGridView) findViewById(R.id.releaseSpeek_gv);
        choose = (TextView) findViewById(R.id.releaseSpeek_choose);//添加图片
        choose.setOnClickListener(this);

        location = (TextView) findViewById(R.id.releaseSpeek_location);
        look_type = (TextView) findViewById(R.id.releaseSpeek_look_type);

        release = (Button) findViewById(R.id.releaseSpeek_release);
        release.setOnClickListener(this);

        adapter = new ReleaseSpeekAdapter(this);
        gv.setAdapter(adapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(ReleaseSpeekActivity.this, FastChoosePhotoActivity.class);
                intent.putParcelableArrayListExtra("choose_image", medias);
                startActivityForResult(intent, 1);
            }
        });

        switch (releaseType){
            case 0:
                titleBa.setTitle("发布享说", 0);
                break;
            case 1:
                titleBa.setTitle("发布", 0);
                location_rl.setVisibility(View.GONE);
                break;
        }

        initData();

    }

    private void initData(){
        speekBeanList = LiteOrmDBUtil.getLiteOrm(this).getQueryAll(SpeekBean.class);
        if (speekBeanList != null && speekBeanList.size() >0) {

            dialog = DialogUtils.getUtils().showDialogAll(this, false, "", "有未发布的信息, 是否继续?", "取消", "继续", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.cancel();
                    SpeekBean b = speekBeanList.get(0);

                    edit.setText(b.getContent());
                    location.setText(b.getShareLocation());

                    String imageAll = b.getShareImgs();
                    if (!TextUtils.isEmpty(imageAll)){
                        imageList  = Arrays.asList(imageAll.split(";"));
                        adapter.setData(imageList);
                        gv.setVisibility(View.VISIBLE);
                        choose.setVisibility(View.GONE);
                    }
                    for (String s : imageList){
                        MediaBean mediaBean = new MediaBean();
                        mediaBean.setThumbnailBigPath(s);
                        medias.add(mediaBean);
                    }


                    LiteOrmDBUtil.getLiteOrm(ReleaseSpeekActivity.this).deleteAll(SpeekBean.class);

                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.cancel();
                    if (speekBeanList != null && speekBeanList.size() > 0) {
                        //取消则删除之前的保存
                        LiteOrmDBUtil.getLiteOrm(ReleaseSpeekActivity.this).deleteAll(SpeekBean.class);
                    }
                }
            });
        }


    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.releaseSpeek_choose://选择图片
                chooseImage();
                break;
            case R.id.releaseSpeek_location_rl://选择位置
                locationS = location.getText().toString();
                if (TextUtils.isEmpty(locationS)){
                    if (TextUtils.isEmpty(saveLocation)){
                        getLocation();
                    }else {
                        location.setText(saveLocation);
                    }
                }else {
                    location.setText("");
                    location.setHint("所在位置");//相当于取消位置选择
                }
                break;
            case R.id.releaseSpeek_look_rl://选择谁可以看

                break;
            case R.id.releaseSpeek_release://发布
                if (!NetwotkUtil.isConnectInternet()){
                    UCommonUtil.getUtil().showToast(this, "网络连接异常");
                    return;
                }

                if (!isAllow){
                    UCommonUtil.getUtil().showToast(this, "正在提交...");
                    return;
                }
                getData();
                if (TextUtils.isEmpty(editString) && (medias.size() <= 0)){
                    UCommonUtil.getUtil().showToast(this, "请输入文字或选择图片");
                    return;
                }
                LoadingUtils.getUtils().loading(this);
                isAllow = false;
                compressAndPost();
                break;
        }

    }

    private void getData(){
        editString = edit.getText().toString();
        locationS = location.getText().toString();
    }

    /**
     * 压缩图片提交oss
     * */
    private void compressAndPost(){
        /**
         * 图片现在本地压缩
         * */
        if (imageList != null && imageList.size() >0){
            UCommonUtil.getUtil().compressImageMulti(this, 300, imageList, new OnMultiCompressListener() {
                @Override
                public void onStart() {
                }
                @Override
                public void onSuccess(List<File> fileList) {
                    imageList.clear();
                    for (File file : fileList){
                        try {
                            imageList.add(file.getAbsolutePath());
                            Log.d("yasuo", "压缩后="+file.getAbsolutePath());
                            Log.d("yasuo", "压缩后="+UCommonUtil.getUtil().getFileSize(file));
                        } catch (Exception e) {
                            e.printStackTrace();
                            return;
                        }
                    }
                    if (imageList != null && imageList.size() >0){
                        toOss();
                    }else {
                        putToHttp();
                    }
                }
                @Override
                public void onError(Throwable e) {
                    LoadingUtils.getUtils().hide();
                    toOss();//直接上传原图
                }
            });
        }else {
            putToHttp();
        }
    }

    private void toOss(){
        //如果上传是一张图片 获取图片宽高
        if (imageList.size() ==1){
            int[] ints = ImageManagerUtils.getUtils().getImageWH(imageList.get(0));
            imgsWidth = ints[0];
            imgsHeight = ints[1];
            Log.d("jjf", "宽="+ints[0]+"=高="+ints[1]);
        }


        OSSManager.getOSSManager().putAsyncFiles(OSSManager.OSS_SHARE, imageList, new OSSManager.OSSListener() {
            @Override
            public void onProgress(long currentSize, long totalSize) {
                //不是整个集合图片的上传进度，是单张图片的上传进度
            }
            @Override
            public void onSuccess(List<String> ossList) {
                //上传oss成功返回的oss图片地址集合 因为地址需要拼接在一起，所以将objectKey取出提交给服务器，使用时加上BaseConfig.OSS_COM_IMAGE
                //单张图片提交时，是全地址
                //将图片集合按照自己服务器格式要求上传  格式 urlA;urlB;

                StringBuilder stringBuilder  = new StringBuilder();
                if (ossList != null  && ossList.size() >0){
                    for (int i = 0; i< ossList.size(); i++){
                        String ossUrl = ossList.get(i);
                        if (i != 0){
                            stringBuilder.append(";");
                        }
                        stringBuilder.append(ossUrl);
                    }
                    if (stringBuilder!= null){
                        roll_imgs = stringBuilder.toString();
                    }
                }
                //拼接完成 将所有信息提交到自己服务器
                putToHttp();
            }
            @Override
            public void onFailure(String message) {
                Log.d("ucw", "提交失败="+message);
                LoadingUtils.getUtils().hide();
                isAllow = true;
                UCommonUtil.getUtil().showToast(ReleaseSpeekActivity.this, "提交失败");
            }
        });
    }

    /**
     * 开始提交网络信息
     * */
    private void putToHttp(){
        MapRequest map = new MapRequest();

        if (imgsWidth >0 && imgsHeight >0){
            map.put(BaseConfig.IMGS_WIDTH, imgsWidth);
            map.put(BaseConfig.IMGS_HEIGHT, imgsHeight);
        }

        switch (releaseType){
            case 0://发布享说
                map.put(BaseConfig.UID, UCommonUtil.getUtil().getId());
                map.put(BaseConfig.NICK_NAME, UChengApplication.nickName);
                map.put(BaseConfig.USER_AVATAR, UChengApplication.userAvatar);
                map.put(BaseConfig.CONTENT, editString);
                map.put(BaseConfig.SHARE_LOCATION, locationS);
                map.put(BaseConfig.SHARE_IMGS, roll_imgs);
                break;

            case 1://发布话题的信息
                map.put(BaseConfig.TOPIC_CONTENT, editString);
                map.put(BaseConfig.TOPIC_IMGS, roll_imgs);
                map.put(BaseConfig.BANNER_ID, themeId);
                break;
        }

        post(map);
    }

    /**
     * 提交
     * */
    private void post(MapRequest map){
        IHttpManager.RequestMethod method = null;
        String url = "";
        switch (releaseType){
            case 0://发布享说
                method = UUConfig.Speek.release_method;
                url = UUConfig.Speek.URL;
                break;
            case 1://发布话题的分享
                method = ThemeConfig.ThemeShare.method_post;
                url = ThemeConfig.ThemeShare.URL;

                break;
        }
        if (method ==null || TextUtils.isEmpty(url)){
            UCommonUtil.getUtil().showToast(this, "信息异常");
            return;
        }

        HttpManager.newInstance(this).query(method, url, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                LoadingUtils.getUtils().hide();
                isAllow = true;

                Log.d("jjf", "发布信息=status="+status+"==msg=="+msg);
                UCommonUtil.getUtil().showToast(ReleaseSpeekActivity.this, "提交失败");
            }

            @Override
            public void onResp(int status,  String msg, String data) {
                LoadingUtils.getUtils().hide();

                Log.d("jjf", "发布信息=status="+status+"==msg=="+msg);
                if (status != 0){
                    UCommonUtil.getUtil().showToast(ReleaseSpeekActivity.this, msg);
                    return;
                }
                BaseConfig.isRelease = true;
                ReleaseSpeekActivity.this.finish();
            }
        });
    }

    /**
     * 选择图片
     * */
    private void chooseImage(){
        UCommonUtil.getUtil().openGalleryMultiple(this, FastChoosePhotoActivity.MAX_IMAGES - hasImageNum,new RxBusResultSubscriber<ImageMultipleResultEvent>() {
            @Override
            public void onEvent(ImageMultipleResultEvent event)   {
                //选择图片点击确定完成时的操作
                int num = 0;
                if (event.getResult() != null){
                    num = event.getResult().size();
                    medias.clear();
                    medias.addAll(event.getResult());

                    if (num > 0){
                        Intent intent = new Intent(ReleaseSpeekActivity.this, FastChoosePhotoActivity.class);
                        intent.putParcelableArrayListExtra("choose_image", medias);
                        startActivityForResult(intent, 1);
                    }
                }
                Log.d("jjf", "已选择" + event.getResult().get(0).getOriginalPath());
            }
        },null, null);
    }


    /**
     * 获取当前位置
     * */
    private void getLocation(){
        PermissionUtils.getUtils().checkLocation(this, new PermissionsListener() {
            @Override
            public void onSuccess() {
                MapManager.getMapManager().startLocation(new AMapLocationListener() {
                    @Override
                    public void onLocationChanged(AMapLocation aMapLocation) {
                        Log.d("ucw", "定位="+aMapLocation.toString());
                        if (aMapLocation != null){
                            saveLocation = aMapLocation.getAddress();
                            locationS = aMapLocation.getAddress();
                            location.setText(locationS);
                        }
                    }
                });
            }

            @Override
            public void onFailed() {
                UCommonUtil.getUtil().showToast(ReleaseSpeekActivity.this, "缺少定位权限");
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        MapManager.getMapManager().stopLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MapManager.getMapManager().desLocation();
        RxGalleryListener.getInstance().setMultiImageCheckedListener(null);
    }

    @Override
    public void onBackPressed() {
        back();
    }

    private void back(){
        UCommonUtil.getUtil().hideSoftInput(this, edit);
        getData();

        if (!TextUtils.isEmpty(editString) || !TextUtils.isEmpty(locationS) || (imageList != null && imageList.size()>0)){
            popupUtils = PopupUtils.getUtils().initRelease(this, titleBa).setClickListener(new PopupUtils.PopupOnItemListener() {
                @Override
                public void onClick(boolean isTop, String type) {
                    switch (type){
                        case "保存":
                            UCommonUtil.getUtil().showToast(ReleaseSpeekActivity.this, type);
                            StringBuffer buffer = new StringBuffer();
                            if (imageList != null && imageList.size() >0){
                                for (String s : imageList){
                                    buffer.append(s+";");
                                }

                            }

                            SpeekBean speekBean = new SpeekBean();
                            speekBean.setContent(editString);
                            speekBean.setShareLocation(locationS);
                            speekBean.setShareImgs(buffer.toString());

                            if (speekBeanList != null && speekBeanList.size() >0){
                                //说明之前保存的有 删除 重新插入
                                LiteOrmDBUtil.getLiteOrm(ReleaseSpeekActivity.this).deleteAll(SpeekBean.class);
                            }
                            LiteOrmDBUtil.getLiteOrm(ReleaseSpeekActivity.this).insert(speekBean);
                            ReleaseSpeekActivity.this.finish();
                            break;
                        case "不保存":
                            if (speekBeanList != null && speekBeanList.size() >0){
                                //说明之前保存的有 删除 重新插入
                                LiteOrmDBUtil.getLiteOrm(ReleaseSpeekActivity.this).deleteAll(SpeekBean.class);
                            }
                            ReleaseSpeekActivity.this.finish();
                            break;
                        case "取消":
                            break;
                    }
                }
                @Override
                public void onDismiss() {
                }
            });

        }else {
            this.finish();
        }
    }

    //得到本地返回的图片地址集合 提交到oss
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        imageList = new ArrayList<>();
        if (requestCode == 1 && resultCode == 1){
            medias = data.getParcelableArrayListExtra("choose_image");
            if (medias != null && medias.size()>0){

                hasImageNum = medias.size();//返回的图片的数量
                for (MediaBean bean : medias){
                    if (!TextUtils.isEmpty(bean.getThumbnailBigPath())){
                        imageList.add(bean.getThumbnailBigPath());
                        Log.d("jjj", "图片大小="+bean.getThumbnailBigPath());
                    }else {
                        imageList.add(bean.getOriginalPath());
                    }
                }

                gv.setVisibility(View.VISIBLE);
                if (adapter == null){
                    adapter = new ReleaseSpeekAdapter(this);
                    gv.setAdapter(adapter);
                }

                adapter.setData(imageList);
                choose.setVisibility(View.GONE);

            }else {
                hasImageNum = 0;//返回的图片的数量
                choose.setVisibility(View.VISIBLE);
                gv.setVisibility(View.GONE);
            }
        }
    }


}
